<?php

namespace app\admin\controller\kzvote;

use app\common\controller\Backend;
use app\common\model\kzvote\gift\Order;
use app\common\model\kzvote\Person;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Vote extends Backend
{
    protected $relationSearch = true;

    /**
     * Vote模型对象
     * @var \app\common\model\kzvote\Vote
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\kzvote\Vote;
        $this->view->assign("moldList", $this->model->getMoldList());
        $this->view->assign("dayLimitStatusList", $this->model->getDayLimitStatusList());
        $this->view->assign("verifyStatusList", $this->model->getVerifyStatusList());
        $this->view->assign("applyStatusList", $this->model->getApplyStatusList());
        $this->view->assign("endApplyStatusList", $this->model->getEndApplyStatusList());
        $this->view->assign("giftStatusList", $this->model->getGiftStatusList());
        $this->view->assign("groupStatusList", $this->model->getGroupStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("checkList", $this->model->getCheckList());
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("applyCheckList", $this->model->getApplyCheckList());
        $this->view->assign("fansStatusList", $this->model->getFansStatusList());
        require_once ROOT_PATH . 'addons/kzvote/helper.php';
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['user'])
                ->where('is_temp',0)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 经典案例
     */
    public function case()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['user'])
                ->where('is_temp',0)
                ->where('case','1')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $link = $this->request->post("link/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['check'] = '1';
                    $params['er_code']   = '';
                    if(isset($link['name']) && $link['name']){
                        $params['link'] = json_encode($link);
                    }else{
                        unset($params['link']);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    //二选一的时候创建作品
                    if ($this->model->mold == '4'){
                        $person = [
                            [
                                'vote_id' => $this->model->id,
                                'code' => 1,
                                'name' => $params['blue'],
                                'status' => '20',
                            ],
                            [
                                'vote_id' => $this->model->id,
                                'code' => 2,
                                'name' => $params['red'],
                                'status' => '20',
                            ]
                        ];
                        (new Person)->saveAll($person);
                    }

                    Db::commit();
                    //生成小程序二维码
                    kzvote_qrCode($this->model, $this->model->id, 'pages/vote/index');
                } catch (ValidateException|PDOException|\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        二选一投票需要做特殊处理
        if ($row['mold'] == '4'){
            $person = Person::where('vote_id',$row->id)->order('code asc')->select();
            $row['blue'] = $person[0]['name'];
            $row['red'] = $person[1]['name'];
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $link = $this->request->post("link/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(isset($link['name']) && $link['name']){
                        $params['link'] = json_encode($link);
                    }else{
                        unset($params['link']);
                    }
                    $result = $row->allowField(true)->save($params);
                    if (!$row->er_code){
                        //生成小程序二维码
                        kzvote_qrCode($row, $row->id, 'pages/vote/index');
                    }
                    if ($row['mold'] == '4'){
                        if ($row['blue'] != $params['blue']){
                            Person::where('vote_id',$row['id'])->where('code',1)->update(['blue'=>$params['blue']]);
                        }
                        if ($row['red'] != $params['red']){
                            Person::where('vote_id',$row['id'])->where('code',2)->update(['red'=>$params['red']]);
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if($this->request->isPost()){
            (new \app\common\model\kzvote\Group())->where('vote_id','in',$ids)->delete();
            (new \app\common\model\kzvote\Person())->where('vote_id','in',$ids)->delete();
            (new \app\common\model\kzvote\Log())->where('vote_id','in',$ids)->delete();
            (new \app\common\model\kzvote\Review())->where('vote_id','in',$ids)->delete();
            (new Order())->where('vote_id','in',$ids)->delete();
        }

        parent::del();
    }

    public function copy($ids){
        $model = $this->model->get($ids)->toArray();
        unset($model['id']);
        unset($model['user_id']);
        unset($model['count']);
        unset($model['hit']);
        unset($model['hit']);
        unset($model['hit']);
        unset($model['person_count']);
        unset($model['er_code']);
        unset($model['person_count']);
        if($model['link']){
            $model['link'] = json_encode($model['link']);
        }
        if ($model['mold'] > '2'){
            $person = Person::where('vote_id',$ids)->order('code asc')->select();
            $data = [];
            foreach ($person as $key => $value){
                $data[$key] = [
                    'vote_id' => $model['id'],
                    'code' => $value['code'],
                    'name' => $value['name'],
                    'status' => '20',
                ];
            }
            (new Person())->saveAll($data);
        }
        $vote = new \app\common\model\kzvote\Vote();
        if ($vote->allowField(true)->save($model)){
            //生成小程序二维码
            kzvote_qrCode($vote, $vote->id, 'pages/vote/index');
            $this->success('复制成功');
        }
        $this->error('复制失败');
    }

    /**
     * 重新生成小程序码
     */
    protected function erCode($ids){
        $model = $this->model->get($ids);
        if (!$model){
            $this->error('活动不存在');
        }
        $model->er_code = '';
        $model->save();
        // 创建活动小程序码
        $url = kzvote_qrCode($model,$model->id,'pages/vote/index');
        if ($url){
            $this->success('生成成功','',['url' => $url]);
        }
        $this->error('生成失败');
    }
}
